var TABLE_PROJECT = 'Project';
var TABLE_CATEGORY='Category';
var TABLE_COMMENT='Comment';
var TABLE_PROJECT='Project';
var TABLE_PROJECTMATERIAL='ProjectMaterial';
var TABLE_PROJECTSTEP='ProjectStep';
var TABLE_PROJECTTOOL='ProjectTool';
var TABLE_PROJECTCONTRACTOR = 'ProjectContractor';
var TABLE_RATE='rate';
var TABLE_TOOL='Tool';
var TABLE_USER='User';
var TABLE_USERPROJECT='UserProject';
var TABLE_USERTOOL='UserTool';
var searchKey='';

//call when display any data get from parse
function stripTags(str){
    if(typeof(str)=='string'){
        str=str.replace(/<br>/gi, "\n");
        str=str.replace(/<p.*>/gi, "\n");
        str=str.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) ");
        str=str.replace(/<(?:.|\s)*?>/g, "");
        return str;
    }
    if(str==null||str==undefined)return 'N/A';
    return str;

}

function linkProject(projectId){
    return baseurl+'project/detail.php?id='+projectId;
}

function linkEditProject(projectId){
   return baseurl+'project/edit.php?id='+projectId;
}

function setActiveTopMenu(tabSelectorIndex){
    $('._topMenu:eq('+tabSelectorIndex+')').addClass('active');
}

function setActive2ndMenu(tabSelectorIndex){
    $('._topMenu2:eq('+tabSelectorIndex+')').addClass('active');
}
function displayNoData(selector,message){
    $(selector).html('<div class="nodata">'+message+'</div>');
}
function displayProject(results){
    //alert('display'+results.length);
	var prolist ='';
        var currentUser = Parse.User.current();
        if (_currentUser) {
            for(var i=0; i<results.length; i++){
            prolist = '<div class="grid">'+
                	'<div class="img"><a href="#"><img src="images/data/image1.jpg" alt="image"></a></div>'+
                    '<div class="g-content">'+
                    	'<div class="g-row"><a class="g-title" href ="'+baseurl+'project/detail.php?id='+results[i].id+'">'+results[i].get("title")+'</a></div>'+
                        '<div class="g-row"><label>Budget:</label> '+Number(results[i].get("cost"))+'$</div>'+
                        '<div class="g-row"><label>Category:</label>'+ results[i].get('categoryId')+'</div>' +//bo qua description
                        '<div class="g-row"><label>Time span:</label> '+stripTags(results[i].get("time"))+'</div>'+
                        '<div class="g-row">'+
                        	'<div class="star-outer" id="rate_project_'+results[i].id+'">'+
                            
                            '</div>'+
                        '</div>'+
                    '</div>'+
                    '<div class="desc">'+   
                    	stripTags(results[i].get("description"))+
                    '</div>'+
                '</div>';
                 $('#project-list').append(prolist);
                var currentRate = Number(results[i].get("rateScore")/results[i].get("rateTotal"));
                if(currentRate>5){
                    currentRate = 5;
                }
                $('#rate_project_'+results[i].id).ratings(5,currentRate,false);
	  }
        }else{
             for(var i=0; i<results.length; i++){
                prolist = '<div class="grid">'+
                	'<div class="img"><a href="#login" class="modalbox"><img src="images/data/image1.jpg" alt="image"></a></div>'+
                    '<div class="g-content">'+
                   	'<div class="g-row"><a class="g-title modalbox" href ="#login">'+results[i].get("title")+'</a></div>'+
                        '<div class="g-row"><label>Budget:</label> '+Number(results[i].get("cost"))+'$</div>'+
                        '<div class="g-row"><label>Category:</label>'+ results[i].get('categoryId')+'</div>' +//bo qua description
                        '<div class="g-row"><label>Time span:</label> '+stripTags(results[i].get("time"))+'</div>'+
                        '<div class="g-row">'+
                        	'<div class="star-outer" id="rate_project_'+results[i].id+'">'+
                            
                            '</div>'+
                        '</div>'+
                    '</div>'+
                    '<div class="desc">'+   
                    	stripTags(results[i].get("description"))+
                    '</div>'+
                '</div>';
                 $('#project-list').append(prolist);
                var currentRate = Number(results[i].get("rateScore")/results[i].get("rateTotal"));
                if(currentRate>5){
                    currentRate = 5;
                }
                $('#rate_project_'+results[i].id).ratings(5,currentRate,false);
        }
	}
	
	return prolist;
}

function displayRecentProject(results){
	var prolist ='';
            for(var i=0; i<results.length; i++){
                /*<li><a href="#">This is one project in my library project</a></li>*/
	  prolist= prolist+'<li>'+
				'<a href="#">'+stripTags(results[i].get("title"))+'</div>'+
				'</li>';
	  }
      return prolist;
   }
   
 function displayRecentTool(results){
	var prolist ='';
            for(var i=0; i<results.length; i++){
	  prolist= prolist+
				'<div class="block-content"><div class="project">'+
				'<div class="project-name">'+stripTags(results[i].get("name"))+'</div>'+
				'</div></div>';
	  }
      return prolist;
   }

function headeraction(){
    /*login function */
	$('#loginbutton').click(function(){
		var username = $('#username_signin').val();
		var password = $('#password_signin').val();
		if(password.length<1){
			$('#passworderror_signin').html('Please input password');
		}
        if(username.length<1){
			$('#passworderror_signin').html('Please input username');
		}
        //alert('x');
		if(username!='' && password !=''){
                    Parse.User.logIn(username, password, {
                    success: function(user) { 
                        loginAPI(username,password);
                        return;
                        window.location = baseurl;
                    },
                    error: function(user, error) {
                      // The login failed. Check error to see why.
                      //alert("Error: " + error.message);
                      if(error)
                      $('#passworderror_signin').html('Error: '+error.message);
                      else{
                        $("#passworderror_signin").html('Network error');
                      }
                    }
                  });
		}
	}); 
    
    $('#forgotpassword').click(function(){
        var username = $('#email_to_reset').val();
        if(username.length<1){
			$('#password_reset_error').html('You must enter your username/email');
		}
           Parse.User.requestPasswordReset(username, {
              success: function() {
                // Password reset request was sent successfully
                $.fancybox.close();
                alert('Password reset successfully. Please check your email.');
                
              },
              error: function(error) {
                // Show the error message somewhere
                if(error.message){
                    $('#password_reset_error').html('Error: '+error.message);
                }
                else{
                    $('#password_reset_error').html('Network error.');
                }
              }
            }); 
    });
        
       /* search advance function*/
	$('#searchadvance').click(function(){
	var Project = Parse.Object.extend("Project");
	var query = new Parse.Query(Project);
	var budget = $("#budget").val();
	var keyword = $("#keyword").val();
	var contributor = $("#contributor").val();
	var prolist;
	prolist='<div class="block-header">Project</div>';
	if(budget !=''){
	query.equalTo("cost", parseFloat(budget));
	}
	if(keyword !=''){
	query.equalTo("title", keyword);
	}
	if(contributor !=''){
	query.equalTo("contributor", contributor);
	}
	query.find({
	  success: function(results) {
	  prolist = prolist + displayProject(results);
	  $("#login").html(prolist);
	  },
	  error: function(error) {
		//alert("Error: " + error.code + " " + error.message);
	  }
	});
	});
        
       
	
}

function displayColumnRight(){
    var ProjectRecent = Parse.Object.extend(TABLE_PROJECT);
	var query = new Parse.Query(ProjectRecent);
    query.descending("createdAt");
    query.limit(5);
	query.find({
	  success: function(results) {	  
		  prolist = displayRecentProject(results);
		  $("#project-list_right").html(prolist);
          //alert('success');
	  },
	  error: function(error) {
		//alert("Error: " + error.code + " " + error.message);
        displayNoData('#project-list','No data found');
	  }
	});
    
    var ToolRecent = Parse.Object.extend("Tool");
	var querytool = new Parse.Query(ToolRecent);
    querytool.descending("createdAt");
    querytool.limit(5);
    
	var toollist='<div class="block-header">Recent Tools</div><div class="block-content">';
	querytool.find({
	  success: function(results) {	  
		  toollist = toollist + displayRecentTool(results)+'</div>';
		  $("#recentTool").html(toollist);
	  },
	  error: function(error) {
		//alert("Error: " + error.code + " " + error.message);
        displayNoData('#recentTool','No data found');
	  }
	});
	
}

function validFormTextField(formSelector,listnames,errorSelector,message){
    if(message==undefined) message = 'You must field all field';
    for(var i =0;i<listnames.length;i++){
        str = $(formSelector+'input[name='+listnames[i]+']').val();
        if(str.length<1){
            $(errorSelector).html(message);
            return false;
        }
    }
    return true;
}

function clearFormTextField(formSelector,listnames){
    for(var i =0;i<listnames.length;i++){
        $(formSelector+' input[name='+listnames[i]+']').val('');

    }
}

function noData(string){
    return '<div class= "nodata">'+string+'</div>';
}
//Huong's comment: 'just a test function, should be remove
function printOut(obj){
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }
    alert(out);
}

$(document).ready(function(){
    //logout block
   if (_currentUser) {
            $('#userheader').html('<ul><li><a><span class="icon-circle"></span>Welcome '+_currentUser.get('username')+'</a></li>'+
              '<li><a id="logout">Logout</a></li></ul>');
        }
   else{
        $('._show_login_popup').attr('href','#login');
        $('._show_login_popup').addClass('modalbox');
   }  
   $('.actionCancel').click(function(){
    $.fancybox.close();
    return false;
    });
    
    /*logout function */
        $('#logout').click(function(){
            Parse.User.logOut();
            window.location = baseurl;
        });
        $('.custom-fancy-close').click(function(){
           $.fancybox.close(); 
        });
        $('.actionCancel').click(function(){
           $.fancybox.close(); 
        });
       /* search function*/
        $('#search-btn').click(function(){
            var keyword = $('#masthead-search-term').val();
            
            if(keyword !=''){
               
                var Project = Parse.Object.extend(TABLE_PROJECT);
            	var query = new Parse.Query(Project);
            	var prolist;
            	//prolist='<div class="block-header">Project</div>';
            	query.contains("title", keyword);
            	query.find({
            	  success: function(results) {
            	  //alert(results.length+' la do dai '); 
            	   prolist = '';
            	    /*if(searchKey!=keyword){
                        $('#project-list').html('');
                    }*/
                    $('#project-list').html('');
            	  prolist = prolist + displayProject(results);
            	  $("#project-list").append(prolist);
                  if(results.length==0)$('#project-list').html(noData('No Project with title '+keyword+' found'));
            	  },
            	  error: function(error) {
            		//alert("Error: " + error.code + " " + error.message);
                   $('#project-list').html(noData('Network error: No Project with title '+keyword+' found'));
            	  }
	});
            $('#viewmore').hide();
            }
            
            searchKey = keyword;
        });  
        headeraction();
});